<template>
  <!-- 有子菜单 -->
  <el-sub-menu 
    v-if="hasChildren && hasPermission" 
    :index="menu.path"
  >
    <template #title>
      <el-icon v-if="menu.icon">
        <component :is="menu.icon" />
      </el-icon>
      <span>{{ menu.title }}</span>
    </template>
    
    <menu-item 
      v-for="child in visibleChildren"
      :key="child.name"
      :menu="child"
    />
  </el-sub-menu>
  
  <!-- 无子菜单 -->
  <el-menu-item 
    v-else-if="!hasChildren && hasPermission" 
    :index="menu.path"
  >
    <el-icon v-if="menu.icon">
      <component :is="menu.icon" />
    </el-icon>
    <template #title>{{ menu.title }}</template>
  </el-menu-item>
</template>

<script setup>
import { computed } from 'vue'
import { useAuthStore } from '@/stores/auth'

const props = defineProps({
  menu: {
    type: Object,
    required: true
  }
})

const authStore = useAuthStore()

// 检查当前菜单是否有权限
const hasPermission = computed(() => {
  if (!props.menu.permission) return true
  return authStore.hasPermission(props.menu.permission)
})

// 检查是否有子菜单
const hasChildren = computed(() => {
  return props.menu.children && props.menu.children.length > 0
})

// 获取有权限的子菜单
const visibleChildren = computed(() => {
  if (!hasChildren.value) return []
  
  return props.menu.children.filter(child => {
    if (!child.permission) return true
    return authStore.hasPermission(child.permission)
  })
})

// 递归组件需要定义name
defineOptions({
  name: 'MenuItem'
})
</script>